package xyz.liuyuhe.StudySpring.ch7.aop;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;

public class AopBeanPostProcessor implements BeanPostProcessor{

    public Object postProcessBeforeInitialization(
            Object bean, String beanName) throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(
            Object bean, String beanName) throws BeansException {
        if(bean.getClass().equals(DBQuery.class)){
            return createProxy(bean);
        }
        
        return bean;
    }

    @SuppressWarnings("unchecked")
    private <T> T createProxy(T bean) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(bean.getClass());
        enhancer.setCallback(new DBQueryInterceptor(bean));
        return (T) enhancer.create();
    }
    
}
